package com.kaxicore.kaxi.controller;

import com.alibaba.fastjson.JSONObject;
import com.kaxicore.kaxi.entity.User;
import com.kaxicore.kaxi.httpResult.Result;
import com.kaxicore.kaxi.httpResult.ResultGenerator;
import com.kaxicore.kaxi.service.UserService;
import com.kaxicore.kaxi.serviceImpl.UserServiceImpl;
import com.kaxicore.kaxi.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/users")
@RestController
@CrossOrigin
public class UserController {

    // 依赖注入
    @Autowired
    private UserService service;

    @Autowired
    private UserServiceImpl userServiceImpl;
    // 这个你也可以不用注解的方式，自己new
    @Autowired
    private User user;

    /**
     * Restful
     */

    // 添加用户
    @PostMapping("/register")
    @ResponseBody
    public Result register(User user) throws Exception {
        if (userServiceImpl.register(user)) {
            return ResultGenerator.genSuccessResult(user);
        }
        return ResultGenerator.genFailResult("用户名已存在！");
    }

    // 登录
    @PostMapping("/login")
    @ResponseBody
    public Result login(User user) throws Exception {
        String userName = user.getUserName();
        String password = user.getPassword();
        User result = userServiceImpl.login(userName, password);
        System.out.println(result);
        if(result == null){
            if (!result.getPassword().equals(password)) {
                return ResultGenerator.genFailResult("密码错误！");
            }
            return ResultGenerator.genFailResult("用户不存在，请前往注册！");
        }else {
            String token = TokenUtil.sign(userName);
            result.setToken(token);
            return ResultGenerator.genSuccessResult(result);
        }
    }

}